package com.baidu.bas.func;

import com.baidu.bas.core.query.Condition;
import com.baidu.bas.core.view.TableQueryVo;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Joiner;
import lombok.val;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Component;
import org.ssssssss.magicapi.config.MagicFunction;
import org.ssssssss.script.annotation.Comment;
import org.ssssssss.script.annotation.Function;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * FIXME 只有简单类型支持这种方式,还要考虑sql注入的问题
 * @author liuzhenchuan@foxmail.com
 * @date 2021/1/4
 */
@Component
public class WhereBuilder implements MagicFunction {

    @Resource
    private ObjectMapper objectMapper;

    @Function
    @Comment("转换为where条件")
    public String query_to_where(@Comment("目标值") Object map, @Comment("目标值") boolean underline) {
        TableQueryVo vo = objectMapper.convertValue(map, TableQueryVo.class);
        return query_to_where(vo,underline);
    }

    public static String query_to_where(TableQueryVo vo, boolean underline) {
        List<Condition> conditions = vo.getCondition();
        if(CollectionUtils.isEmpty(conditions)){
            return "";
        }
        List<String> clauses = new ArrayList<>();
        conditions.stream().filter(it->it.getValue()!=null).forEach(cond->{
            Object value = cond.getValue();
            StringBuilder sb = new StringBuilder();
            String key = cond.getKey();
            if(cond.getOperator().isIn()){
                if(value instanceof Collection){
                    val col = (Collection)value;
                    if(CollectionUtils.isEmpty(col)){
                        return;
                    }
                    sb.append(key).append(" ").append("in").append(" (");
                    Object innerItem = col.iterator().next();
                    if(innerItem instanceof String){
                        sb.append(col.stream().map(it->"'" + it + "'").collect(Collectors.joining(",")));
                    }else{
                        sb.append(col.stream().collect(Collectors.joining(",")));
                    }
                    sb.append(" )");
                }
            }
            if(cond.getOperator().isEq()){
                if(value instanceof String){
                    sb.append(key).append(" ").append("=").append(" ").append("'").append(value).append("'");
                }else{
                    sb.append(key).append(" ").append("=").append(" ");
                }
            }
            if(!sb.toString().isEmpty()){
                clauses.add(sb.toString());
            }

        });
        return Joiner.on(" and ").join(clauses);
    }

}
